<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google OAuth & JWT 认证测试</title>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fafafa;
        }
        h1 { color: #333; text-align: center; }
        h2 { color: #555; }
        button {
            background: #4285f4;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #3367d6; }
        button:disabled { background: #ccc; cursor: not-allowed; }
        .btn-danger { background: #dc3545; }
        .btn-danger:hover { background: #c82333; }
        .btn-success { background: #28a745; }
        .btn-success:hover { background: #218838; }
        input, textarea {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .user-info {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .hidden { display: none; }
        .google-signin-button {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }
        .auth-status {
            text-align: center;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .authenticated {
            background: #d4edda;
            color: #155724;
        }
        .unauthenticated {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 Google OAuth & JWT 认证测试</h1>
        
        <!-- 认证状态 -->
        <div id="auth-status" class="auth-status unauthenticated">
            ❌ 未登录
        </div>
        
        <!-- Google登录部分 -->
        <div class="section">
            <h2>🔑 Google OAuth 登录</h2>
            <div id="google-signin-section">
                <div id="google-signin-button" class="google-signin-button"></div>
                <p><em>点击上方按钮使用Google账户登录</em></p>
            </div>
        </div>
        
        <!-- 本地登录部分 -->
        <div class="section">
            <h2>📧 本地账户登录</h2>
            <div>
                <h3>注册新账户</h3>
                <input type="text" id="register-username" placeholder="用户名（可选）">
                <input type="email" id="register-email" placeholder="邮箱地址">
                <input type="password" id="register-password" placeholder="密码（至少6位）">
                <input type="text" id="register-firstname" placeholder="名字（可选）">
                <input type="text" id="register-lastname" placeholder="姓氏（可选）">
                <button onclick="register()">注册</button>
            </div>
            
            <div style="margin-top: 20px;">
                <h3>账户登录</h3>
                <input type="email" id="login-email" placeholder="邮箱地址">
                <input type="password" id="login-password" placeholder="密码">
                <button onclick="login()">登录</button>
            </div>
        </div>
        
        <!-- 用户信息部分 -->
        <div class="section hidden" id="user-section">
            <h2>👤 用户信息</h2>
            <button onclick="getCurrentUser()">获取用户信息</button>
            <button onclick="refreshToken()" class="btn-success">刷新Token</button>
            <button onclick="logout()" class="btn-danger">登出</button>
            
            <div style="margin-top: 20px;">
                <h3>修改密码</h3>
                <input type="password" id="old-password" placeholder="原密码">
                <input type="password" id="new-password" placeholder="新密码">
                <button onclick="changePassword()">修改密码</button>
            </div>
        </div>
        
        <!-- 受保护的API测试 -->
        <div class="section hidden" id="protected-api-section">
            <h2>🛡️ 受保护的API测试</h2>
            <button onclick="testProtectedEndpoint()">测试受保护端点</button>
            <button onclick="testUserList()">获取用户列表</button>
            <button onclick="testCreatePost()">创建文章</button>
        </div>
        
        <!-- 结果显示 -->
        <div id="result"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:3379/api/v1';
        let currentUser = null;
        let accessToken = localStorage.getItem('access_token');
        let refreshTokenString = localStorage.getItem('refresh_token');

        // 页面加载时初始化
        window.onload = function() {
            console.log('🚀 初始化认证测试页面');
            
            // 检查现有token
            if (accessToken) {
                console.log('🔍 发现本地token，验证中...');
                getCurrentUser();
            }
            
            // 初始化Google登录
            initializeGoogleSignIn();
            
            // 获取后端配置
            checkBackendConfig();
        };

        // 初始化Google登录
        function initializeGoogleSignIn() {
            // 确保DOM完全加载
            if (document.readyState !== 'complete') {
                setTimeout(initializeGoogleSignIn, 100);
                return;
            }
            
            // 确保Google SDK已加载
            if (typeof google === 'undefined' || !google.accounts || !google.accounts.id) {
                console.log('⏳ 等待Google SDK加载...');
                setTimeout(initializeGoogleSignIn, 200);
                return;
            }
            
            console.log('🔧 开始初始化Google OAuth...');
            
            // 从后端获取Google Client ID
            fetch(`${API_BASE}/auth/config`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('📋 后端配置响应:', data);
                    
                    if (data.success && data.data.googleEnabled && data.data.googleClientId) {
                        console.log('✅ Google配置有效，开始初始化...');
                        
                        try {
                            // 初始化Google Identity Services
                            google.accounts.id.initialize({
                                client_id: data.data.googleClientId,
                                callback: handleGoogleSignIn,
                                auto_select: false,
                                cancel_on_tap_outside: true,
                                use_fedcm_for_prompt: false
                            });
                            
                            // 渲染登录按钮
                            const buttonContainer = document.getElementById('google-signin-button');
                            if (buttonContainer) {
                                google.accounts.id.renderButton(
                                    buttonContainer,
                                    { 
                                        theme: 'outline', 
                                        size: 'large', 
                                        text: 'signin_with', 
                                        shape: 'rectangular',
                                        width: '280',
                                        locale: 'zh-CN'
                                    }
                                );
                                console.log('🎨 Google登录按钮已渲染');
                            }
                            
                            showResult('✅ Google OAuth配置成功！点击上方按钮进行登录', 'success');
                        } catch (initError) {
                            console.error('Google初始化错误:', initError);
                            showResult(`❌ Google初始化失败: ${initError.message}`, 'error');
                        }
                    } else {
                        console.warn('⚠️ Google OAuth未正确配置');
                        showResult('⚠️ Google OAuth未配置或未启用。请检查环境变量设置。', 'error');
                        
                        // 显示配置提示
                        const buttonContainer = document.getElementById('google-signin-button');
                        if (buttonContainer) {
                            buttonContainer.innerHTML = `
                                <div class="alert alert-warning" style="margin: 0; padding: 15px; border-radius: 4px;">
                                    <strong>🔧 Google OAuth 未配置</strong><br>
                                    请在 .env 文件中设置 GOOGLE_CLIENT_ID 和 GOOGLE_CLIENT_SECRET
                                </div>
                            `;
                        }
                    }
                })
                .catch(error => {
                    console.error('获取Google配置失败:', error);
                    showResult(`❌ 无法获取Google配置: ${error.message}`, 'error');
                    
                    // 显示错误信息
                    const buttonContainer = document.getElementById('google-signin-button');
                    if (buttonContainer) {
                        buttonContainer.innerHTML = `
                            <div class="alert alert-danger" style="margin: 0; padding: 15px; border-radius: 4px;">
                                <strong>🚨 连接失败</strong><br>
                                无法连接到后端服务器，请确保服务器运行在 localhost:3379
                            </div>
                        `;
                    }
                });
        }

        // 处理Google登录回调 - 改进错误处理和响应处理
        async function handleGoogleSignIn(response) {
            console.log('🔔 收到Google登录回调:', response);
            
            try {
                // 验证响应格式
                if (!response || !response.credential) {
                    throw new Error('Google响应格式无效：缺少credential');
                }
                
                showResult('🔄 正在处理Google登录凭据...', 'info');
                
                console.log('📤 发送登录请求到后端...');
                const result = await fetch(`${API_BASE}/auth/google`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        credential: response.credential
                    })
                });
                
                console.log('📥 后端响应状态:', result.status);
                
                if (!result.ok) {
                    const errorText = await result.text();
                    throw new Error(`HTTP错误 ${result.status}: ${errorText}`);
                }
                
                const data = await result.json();
                console.log('📋 后端响应数据:', data);
                
                if (data.success) {
                    accessToken = data.data.token;
                    refreshTokenString = data.data.refreshToken;
                    currentUser = data.data.user;
                    
                    // 保存到本地存储
                    localStorage.setItem('access_token', accessToken);
                    if (refreshTokenString) {
                        localStorage.setItem('refresh_token', refreshTokenString);
                    }
                    
                    console.log('✅ 登录数据已保存到本地存储');
                    
                    updateAuthStatus(true);
                    showResult(`🎉 Google登录成功！欢迎 ${currentUser.firstName || currentUser.email}`, 'success');
                    showUserInfo(currentUser);
                    
                    // 自动滚动到用户信息部分
                    document.getElementById('user-section')?.scrollIntoView({ behavior: 'smooth' });
                } else {
                    throw new Error(data.message || '登录失败，未知原因');
                }
            } catch (error) {
                console.error('💥 Google登录处理错误:', error);
                showResult(`❌ Google登录失败: ${error.message}`, 'error');
                
                // 额外的调试信息
                if (error.name === 'TypeError' && error.message.includes('fetch')) {
                    showResult('🔍 提示：请确保后端服务器运行在 localhost:3379 且认证路由已配置', 'info');
                }
            }
        }

        // 注册
        async function register() {
            const username = document.getElementById('register-username').value;
            const email = document.getElementById('register-email').value;
            const password = document.getElementById('register-password').value;
            const firstName = document.getElementById('register-firstname').value;
            const lastName = document.getElementById('register-lastname').value;
            
            if (!email || !password) {
                showResult('邮箱和密码是必需的', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: username || undefined,
                        email,
                        password,
                        firstName: firstName || undefined,
                        lastName: lastName || undefined,
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    accessToken = data.data.token;
                    refreshTokenString = data.data.refreshToken;
                    currentUser = data.data.user;
                    
                    localStorage.setItem('access_token', accessToken);
                    if (refreshTokenString) {
                        localStorage.setItem('refresh_token', refreshTokenString);
                    }
                    
                    updateAuthStatus(true);
                    showResult(`✅ 注册成功！欢迎 ${currentUser.email}`, 'success');
                    showUserInfo(currentUser);
                    
                    // 清空表单
                    document.getElementById('register-username').value = '';
                    document.getElementById('register-email').value = '';
                    document.getElementById('register-password').value = '';
                    document.getElementById('register-firstname').value = '';
                    document.getElementById('register-lastname').value = '';
                } else {
                    showResult(`❌ 注册失败: ${data.message}`, 'error');
                }
            } catch (error) {
                showResult(`💥 注册出错: ${error.message}`, 'error');
            }
        }

        // 登录
        async function login() {
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            
            if (!email || !password) {
                showResult('邮箱和密码是必需的', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ email, password })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    accessToken = data.data.token;
                    refreshTokenString = data.data.refreshToken;
                    currentUser = data.data.user;
                    
                    localStorage.setItem('access_token', accessToken);
                    if (refreshTokenString) {
                        localStorage.setItem('refresh_token', refreshTokenString);
                    }
                    
                    updateAuthStatus(true);
                    showResult(`✅ 登录成功！欢迎回来 ${currentUser.email}`, 'success');
                    showUserInfo(currentUser);
                    
                    // 清空密码框
                    document.getElementById('login-password').value = '';
                } else {
                    showResult(`❌ 登录失败: ${data.message}`, 'error');
                }
            } catch (error) {
                showResult(`💥 登录出错: ${error.message}`, 'error');
            }
        }

        // 获取当前用户信息
        async function getCurrentUser() {
            if (!accessToken) {
                showResult('请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/me`, {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentUser = data.data;
                    updateAuthStatus(true);
                    showResult('✅ 获取用户信息成功', 'success');
                    showUserInfo(currentUser);
                } else {
                    if (response.status === 401) {
                        // Token过期，尝试刷新
                        await attemptTokenRefresh();
                    } else {
                        showResult(`❌ 获取用户信息失败: ${data.message}`, 'error');
                    }
                }
            } catch (error) {
                showResult(`💥 获取用户信息出错: ${error.message}`, 'error');
            }
        }

        // 刷新Token
        async function refreshToken() {
            if (!refreshTokenString) {
                showResult('没有刷新令牌', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/refresh`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        refreshToken: refreshTokenString
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    accessToken = data.data.token;
                    refreshTokenString = data.data.refreshToken;
                    
                    localStorage.setItem('access_token', accessToken);
                    localStorage.setItem('refresh_token', refreshTokenString);
                    
                    showResult('✅ Token刷新成功', 'success');
                } else {
                    showResult(`❌ Token刷新失败: ${data.message}`, 'error');
                    logout(); // 刷新失败则登出
                }
            } catch (error) {
                showResult(`💥 Token刷新出错: ${error.message}`, 'error');
                logout();
            }
        }

        // 尝试自动刷新Token
        async function attemptTokenRefresh() {
            if (refreshTokenString) {
                await refreshToken();
                if (accessToken) {
                    await getCurrentUser(); // 重新获取用户信息
                }
            } else {
                logout();
            }
        }

        // 修改密码
        async function changePassword() {
            const oldPassword = document.getElementById('old-password').value;
            const newPassword = document.getElementById('new-password').value;
            
            if (!oldPassword || !newPassword) {
                showResult('请输入原密码和新密码', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/change-password`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`
                    },
                    body: JSON.stringify({
                        oldPassword,
                        newPassword
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showResult('✅ 密码修改成功', 'success');
                    document.getElementById('old-password').value = '';
                    document.getElementById('new-password').value = '';
                } else {
                    showResult(`❌ 密码修改失败: ${data.message}`, 'error');
                }
            } catch (error) {
                showResult(`💥 密码修改出错: ${error.message}`, 'error');
            }
        }

        // 登出
        function logout() {
            accessToken = null;
            refreshTokenString = null;
            currentUser = null;
            
            localStorage.removeItem('access_token');
            localStorage.removeItem('refresh_token');
            
            updateAuthStatus(false);
            showResult('👋 已登出', 'info');
        }

        // 测试受保护端点
        async function testProtectedEndpoint() {
            if (!accessToken) {
                showResult('请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/me`, {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                
                const data = await response.json();
                showResult(`🛡️ 受保护端点测试结果:\n${JSON.stringify(data, null, 2)}`, data.success ? 'success' : 'error');
            } catch (error) {
                showResult(`💥 受保护端点测试出错: ${error.message}`, 'error');
            }
        }

        // 测试用户列表
        async function testUserList() {
            if (!accessToken) {
                showResult('请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/users`, {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                
                const data = await response.json();
                showResult(`👥 用户列表测试结果:\n${JSON.stringify(data, null, 2)}`, data.success ? 'success' : 'error');
            } catch (error) {
                showResult(`💥 用户列表测试出错: ${error.message}`, 'error');
            }
        }

        // 测试创建文章
        async function testCreatePost() {
            if (!accessToken) {
                showResult('请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/posts`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`
                    },
                    body: JSON.stringify({
                        title: '测试文章 - ' + new Date().toLocaleString(),
                        content: '这是一篇通过JWT认证创建的测试文章。',
                        summary: 'JWT认证测试',
                        authorId: currentUser?.id
                    })
                });
                
                const data = await response.json();
                showResult(`📝 创建文章测试结果:\n${JSON.stringify(data, null, 2)}`, data.success ? 'success' : 'error');
            } catch (error) {
                showResult(`💥 创建文章测试出错: ${error.message}`, 'error');
            }
        }

        // 检查后端配置
        async function checkBackendConfig() {
            try {
                const response = await fetch(`${API_BASE}/auth/config`);
                const data = await response.json();
                
                if (data.success) {
                    console.log('✅ 后端配置:', data.data);
                } else {
                    console.warn('⚠️ 获取后端配置失败');
                }
            } catch (error) {
                console.error('❌ 检查后端配置出错:', error);
            }
        }

        // 更新认证状态显示
        function updateAuthStatus(isAuthenticated) {
            const statusEl = document.getElementById('auth-status');
            const userSection = document.getElementById('user-section');
            const protectedSection = document.getElementById('protected-api-section');
            
            if (isAuthenticated) {
                statusEl.textContent = `✅ 已登录 ${currentUser?.email || ''}`;
                statusEl.className = 'auth-status authenticated';
                userSection.classList.remove('hidden');
                protectedSection.classList.remove('hidden');
            } else {
                statusEl.textContent = '❌ 未登录';
                statusEl.className = 'auth-status unauthenticated';
                userSection.classList.add('hidden');
                protectedSection.classList.add('hidden');
            }
        }

        // 显示用户信息
        function showUserInfo(user) {
            const info = `👤 用户信息:
ID: ${user.id}
邮箱: ${user.email}
用户名: ${user.username || '未设置'}
姓名: ${user.firstName || ''} ${user.lastName || ''}
提供商: ${user.provider}
头像: ${user.picture || '无'}
状态: ${user.isActive ? '激活' : '禁用'}
创建时间: ${new Date(user.createdAt).toLocaleString()}`;
            
            showResult(info, 'user-info');
        }

        // 显示结果
        function showResult(message, type = 'info') {
            const resultEl = document.getElementById('result');
            resultEl.textContent = message;
            resultEl.className = `result ${type}`;
            
            // 自动滚动到结果
            resultEl.scrollIntoView({ behavior: 'smooth' });
        }
    </script>
</body>
</html> 